package com.lagou.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取功能名字
        // String methodName = request.getParameter("methodName");
        String methodName = null;
        request.setCharacterEncoding("utf-8");

        // 获取POST请求的Content-Type类型
        String header = request.getHeader("Content-Type");
        // 判断传递的数据是不是json格式
        if("application/json;charset=utf-8".equalsIgnoreCase(header)){
            // 是JSON,把它转换为字符串输出
            String postJSON = getPostJSON(request);
            // 将数据转换为map格式
            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);
            methodName = (String)map.get("methodName");
            // 将获取到的对象，保存到request域对象中
            request.setAttribute("map",map);
        }else{
            methodName = request.getParameter("methodName");
        }
        // 判断要执行的方法
        if(methodName!=null){
            try{
                // 获取字节码文件对象 TestServlet
                Class c = this.getClass();
                // 根据传入的方法名，获取对应的方法对象
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                // 调用invoke方法执行对应的功能
                method.invoke(this,request,response);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * 因为前台如果传过来的数据是一个Json格式,无法通过普通的获取参数的方法得到值，要通过流来读这个json
     * post请求格式为: application/json;charset=utf-8
     */
    public String getPostJSON(HttpServletRequest request){
        try {
            // 1.从request中 获取缓存输入流对象
            BufferedReader reader = request.getReader();
            // 2.创建StringBuffer,来存储获取到的值
            StringBuffer sb = new StringBuffer();
            String line = null;
            while((line = reader.readLine())!=null){
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

}
